$(function () {
    var jgdId = $("[name='jgd.id']").val();
    // 加工单明细的加载
    if (jgdId) {
        mxGrid($.webPath() + '/jggl/jgdgl/jggl_jgdmx?jgdId=' + jgdId);
    }

    // 预期成材明细
    var grid;
    $.post($.webPath() + '/base/sjzdsy/get_sjzdz', {'bm': 'cd'}, function (data) {
        var cdOptions = data;
        yqccmx(cdOptions);
    });

    // 预期成材明细
    function yqccmx(cdOptions) {
        var columns = [
            [
                {field: 'checked', checkbox: true},
                {field: 'id', title: 'ID', hidden: true},
                { title: '物资编码ID', field: 'wzggId', hidden: true},
                {title: '物资编码', field: 'wzggCode', align: 'center', editor: {type: 'text'}, width: 170},
                {title: '物资名称', field: 'wzggName', align: 'center', editor: {type: 'text'}, width: 150},
                {title: '规格型号', field: 'wzggGgxh', align: 'center', editor: {type: 'text'}, width: 150},
                {title: '单位', field: 'dw', align: 'center', editor: {type: 'text'}, width: 50},
                {title: '材质', field: 'cz', align: 'center', editor: {type: 'text'}, width: 100},
                {title: '产地', field: 'cdId', align: 'center', editor: {type: 'combobox', options: {
                    data: cdOptions,
                    valueField: 'id',
                    textField: 'z',
                    panelHeight: '100',
                    width: '80'
                }}, formatter: function (value) {
                    for (var i = 0; i < cdOptions.length; i++) {
                        if (cdOptions[i].id == value) return cdOptions[i].z;
                    }
                    return value;
                }, width: 150},
                {title: '成材数量', field: 'ccsl', align: 'right', editor: {type: 'numberbox', options: {required: true, min: 0, groupSeparator: ',', precision: 0}},
                    formatter: function (value) {
                        var sl = formatSlForHtml(value, ",");
                        return sl;
                    }, width: 150},
                {title: '成材重量', field: 'cczl', align: 'right', editor: {type: 'numberbox', options: {required: true, min: 0, groupSeparator: ',', precision: 4}},
                    formatter: function (value) {
                        var sl = formatSlForHtml(value, ",");
                        return sl;
                    }, width: 150}
            ]
        ];

        var options = {
            toolbar: '#yqcc_mx_toolbar',
            fitColumns: true,
            columns: columns,
            fit: true,
            checkbox: true,
            checkOnSelect: false,
            selectOnCheck: false,
            singleSelect: true,
            rownumbers: true,
            onSelect: function (rowIndex, rowData) {
                datagridOnSelectHandle(rowIndex, rowData);
            },
            onLoadSuccess: function () {
                var obj = {id: "", 'wzggId': "", 'wzgg.oldcode': '', 'wzggCode': '', 'wzggName': '', 'wzggGgxh': '', 'dw': '', 'cdId': '', 'cz': '', 'ccsl': 0, 'cczl': 0};
                $(grid).edatagrid('appendRow', obj);
                $(".datagrid-htable .datagrid-cell").css('text-align', 'center');
            }
        };

        if (jgdId != "") {
            $.extend(options, {url: $.webPath() + '/jggl/jgdgl/jggl_yqccmx?jgdId=' + jgdId});
        } else {
            $.extend(options, {data: {
                rows: [
                    {id: "", 'wzggId': "", 'wzgg.oldcode': '', 'wzggCode': '', 'wzggName': '', 'wzggGgxh': '', 'dw': '', 'cdId': null, 'cz': '', 'ccsl': 0, 'cczl': 0},
                    {id: "", 'wzggId': "", 'wzgg.oldcode': '', 'wzggCode': '', 'wzggName': '', 'wzggGgxh': '', 'dw': '', 'cdId': null, 'cz': '', 'ccsl': 0, 'cczl': 0},
                    {id: "", 'wzggId': "", 'wzgg.oldcode': '', 'wzggCode': '', 'wzggName': '', 'wzggGgxh': '', 'dw': '', 'cdId': null, 'cz': '', 'ccsl': 0, 'cczl': 0},
                    {id: "", 'wzggId': "", 'wzgg.oldcode': '', 'wzggCode': '', 'wzggName': '', 'wzggGgxh': '', 'dw': '', 'cdId': null, 'cz': '', 'ccsl': 0, 'cczl': 0},
                    {id: "", 'wzggId': "", 'wzgg.oldcode': '', 'wzggCode': '', 'wzggName': '', 'wzggGgxh': '', 'dw': '', 'cdId': null, 'cz': '', 'ccsl': 0, 'cczl': 0}
                ]
            }
            })
        }
        grid = $('#yqcc_mx_edatagrid').edatagrid(options);
    }

    //表格处在编辑状态的时候，给表单绑定事件
    function datagridOnSelectHandle(rowIndex, rowData) {
        //获取每个单元格
        $(grid).edatagrid('editRow', rowIndex);
        var editors = $(grid).datagrid('getEditors', rowIndex);
        if (editors.length == 0)
            return;
        var bm1Editor = editors[0]; // 物资编码编辑框
        var mcEditor = editors[1]; // 物资名称
        $(mcEditor.target).attr("readonly", "true");
        var ggEditor = editors[2]; //规格编辑框
        $(ggEditor.target).attr("readonly", "true");
        var dwEditor = editors[3];  // 单位
        $(dwEditor.target).attr("readonly", "true");
        var czEditor = editors[4]; // 材质
        $(czEditor.target).attr("readonly", "true");
        var slEditor = editors[6]; // 数量
        slEditor.target.unbind('blur').bind('blur', function () {
            $(slEditor.target).numberbox('setValue', $(slEditor.target).val());
            rowData.ccsl = $(slEditor.target).val();
        });
        var zlEditor = editors[7]; // 计量
        zlEditor.target.unbind('blur').bind('blur', function () {
            $(zlEditor.target).numberbox('setValue', $(zlEditor.target).val());
            rowData.cczl = $(zlEditor.target).val();
        });
        var cdEditor = editors[5];// 产地编辑框
        $(cdEditor.target).combobox({
            onChange: function (newValue, oldValue) {
                $(cdEditor.target).combobox('setValue', newValue);
                rowData.cdId = newValue;
            }
        });
        $(cdEditor.target).combobox({
            onLoadSuccess: function () {
                if (rowData['cdId'])
                    $(cdEditor.target).combobox('setValue', rowData['cdId']);
            }
        });

        $(bm1Editor.target).unbind('keyup').bind('keyup', function (event) {
            var code = $(bm1Editor.target).val();
            if (event.keyCode == "13") {
                $.post($.webPath() + '/sys/wzbm/search', {code: $(bm1Editor.target).val(), 'page': 1, 'rows': -1}, function (data) {
                    var rows = $("#yqcc_mx_edatagrid").datagrid('getData').rows;
                    var num = 0;
                    for (var i = 0; i < rows.length; i++) {
                        if (rows[i]['wzggCode'] == code) {
                            num++;
                        }
                    }
                    if (num > 0) {
                        $.messager.alert("提示", "您填写的物资编码已重复", "info", function () {
                            setTimeout(function () {
                                $(bm1Editor.target).select();
                            }, 500);

                            return false;
                        });
                    } else {
                        num = 0;
                        if (data.rows.length == 1) {
                            var row = data.rows[0];
                            $(mcEditor.target).val(row.name);
                            $(ggEditor.target).val(row.ggxh);
                            $(cdEditor.target).combobox().next('span').find('input').focus();
                            $(dwEditor.target).val(row.dw);
                            $(czEditor.target).val(row.cz);
                            if (rowIndex >= 1) {
                                var griddata = $(grid).edatagrid('getData');
                                var rows = griddata.rows;
                                if (rows[rowIndex - 1]['cdId']) {
                                    $(cdEditor.target).combobox('setValue', rows[rowIndex - 1]['cdId']);
                                }
                            }
                            rowData['wzggId'] = row.id;
                            var obj = {id: "", 'wzggId': "", 'wzgg.oldcode': '', 'wzggCode': '', 'wzggName': '', 'wzggGgxh': '', 'dw': '', 'cdId': '', 'cz': '', 'ccsl': 0, 'cczl': 0};
                            $(grid).edatagrid('appendRow', obj);
                        } else if (data.rows.length > 1) {
                            for (var i = 0; i < data.rows.length; i++) {
                                var row = data.rows[i];
                                if ($(bm1Editor.target).val() == row.code) {
                                    $(mcEditor.target).val(row.name);
                                    $(ggEditor.target).val(row.ggxh);
                                    $(cdEditor.target).combobox().next('span').find('input').focus()
                                    $(dwEditor.target).val(row.dw);
                                    $(czEditor.target).val(row.cz);
                                    if (rowIndex >= 1) {
                                        var griddata = $(grid).edatagrid('getData');
                                        var rows = griddata.rows;
                                        if (rows[rowIndex - 1]['cdId']) {
                                            $(cdEditor.target).combobox('setValue', rows[rowIndex - 1]['cdId']);
                                        }
                                    }
                                    rowData['wzggId'] = row.id;
                                    var obj = {id: "", 'wzggId': "", 'wzgg.oldcode': '', 'wzggCode': '', 'wzggName': '', 'wzggGgxh': '', 'dw': '', 'cdId': '', 'cz': '', 'ccsl': 0, 'cczl': 0};
                                    $(grid).edatagrid('appendRow', obj);
                                    return false;
                                }
                            }
                            $.messager.alert("提示", "输入的物资编码无物资", "info", function () {
                                setTimeout(function () {
                                    $(bm1Editor.target).select();
                                }, 500);

                                return false;
                            });
                        } else {
                            $.messager.alert("提示", "输入的物资编码无物资", "info", function () {
                                setTimeout(function () {
                                    $(bm1Editor.target).select();
                                }, 500);

                                return false;
                            });
                        }
                    }
                }, 'json');
            }
        })
        $(bm1Editor.target).focus();
    }

    // 新增物资计划明细
    $("#yqcc_mx_toolbar [name='xzyqccmx']").click(function () {
        searchcodewindow(openSearchWindowOKbtnHandle, 1);
    });

    // 新增一行
    $("#yqcc_mx_toolbar [name='xzyqccyh']").click(function () {
        var obj = {id: "", 'wzggId': "", 'wzgg.oldcode': '', 'wzggCode': '', 'wzggName': '', 'wzggGgxh': '', 'dw': '', 'cdId': '', 'cz': '', 'ccsl': 0, 'cczl': 0};
        $(grid).edatagrid('appendRow', obj);
    });

    // 新增五行
    $("#yqcc_mx_toolbar [name='xzyqccwh']").click(function () {
        for (var i = 0; i < 5; i++) {
            var obj = {id: "", 'wzggId': "", 'wzgg.oldcode': '', 'wzggCode': '', 'wzggName': '', 'wzggGgxh': '', 'dw': '', 'cdId': '', 'cz': '', 'ccsl': 0, 'cczl': 0};
            $(grid).edatagrid('appendRow', obj);
        }

    });
    // 新增十行
    $("#yqcc_mx_toolbar [name='xzyqccsh']").click(function () {
        for (var i = 0; i < 10; i++) {
            var obj = {id: "", 'wzggId': "", 'wzgg.oldcode': '', 'wzggCode': '', 'wzggName': '', 'wzggGgxh': '', 'dw': '', 'cdId': '', 'cz': '', 'ccsl': 0, 'cczl': 0};
            $(grid).edatagrid('appendRow', obj);
        }

    });

    // 删除物资计划明细
    $("#yqcc_mx_toolbar [name='scyqccmx']").click(function () {
        var rows = $(grid).edatagrid('getChecked');
        if (rows.length > 0) {
            $.messager.confirm('提示', '是否确定删除物资明细?', function (r) {
                if (r) {
                    $.each(rows, function (i, val) {
                        var index = $(grid).edatagrid('getRowIndex', val);
                        $(grid).edatagrid('deleteRow', index);
                    });
                }
            });
        } else {
            $.messager.alert("提示", "请勾选要删除的物资明细!");
        }
        $(grid).edatagrid('resize');
    });

    //查询物资代码确定按钮回调函数
    function openSearchWindowOKbtnHandle(data) {
        var rowdatas = $.map(data, function (n, i) {
            var temp = {
                'id': '',
                'wzggId': n.id,
                'wzgg.oldcode': n.code,
                'wzggCode': n.code,
                'wzggName': n.name,
                'wzggGgxh': n.ggxh,
                'dw': n.dw,
                'wzggCz': n.cz,
                'cdId': null,
                'cz': n.cz,
                'ccsl': 0,
                'cczl': 0

            };
            return temp;
        });
        $.each(rowdatas, function (i, obj) {
            var rows = $(grid).edatagrid('getRows');
            var flag = false;
            $.each(rows, function (i, objs) {
                if (!objs['wzggCode']) {
                    $(grid).edatagrid('deleteRow', i);
                } else if (obj['wzggCode'] == objs['wzggCode']) {
                    flag = true;
                    return false;
                }
            })
            if (!flag) {
                $(grid).edatagrid('appendRow', obj);
            }
            var obj = {id: "", 'wzggId': "", 'wzgg.oldcode': '', 'wzggCode': '', 'wzggName': '', 'wzggGgxh': '', 'dw': '', 'cdId': '', 'cz': '', 'ccsl': 0, 'cczl': 0};
            $(grid).edatagrid('appendRow', obj);
        });
    }

});

function mxGrid(href) {
    $("#jgd_mx").edatagrid({
        url: href,
        fitColumns: true,
        singleSelect: true,
        fit: true,
        checkbox: false,
        checkOnSelect: false,
        selectOnCheck: false,
        showFooter: true,
        rownumbers: true,
        toolbar: "#jgdgl_jgdmx_toolbar",
        columns: [
            [
                {field: 'khbm', name: 'test', align: 'center', title: '卡号编码', width: 70},
                {field: 'jtwz.code', name: 'test', align: 'center', title: '物资编码', width: 50},
                {field: 'jtwz.name', title: '物资名称', align: 'center', width: 50},
                {field: 'jtwz.ggxh', title: '规格型号', align: 'center', width: 70},
                {field: 'jtwz.dw', title: '单位', align: 'center', width: 20},
                {field: 'cd.z', title: '产地', align: 'center', width: 50},
                {field: 'ck.mc', title: '仓库', align: 'center', width: 50},
                {field: 'sku', title: '标识', align: 'center', width: 50},
                {field: 'jz', title: '件重', align: 'center', hidden: true},
                {field: 'sbsl', align: 'center', editor: {type: 'numberbox', options: {min: 0, precision: 4, groupSeparator: ','}}, title: '申报数量',
                    formatter: function (value) {
                        var sl = formatSlForHtml(value, ",");
                        return sl;
                    },
                    width: 50},
                {field: 'sbzl', align: 'center', editor: {type: 'numberbox', options: {min: 0, precision: 4, groupSeparator: ','}}, title: '申报重量',
                    formatter: function (value) {
                        var zl = formatJeForHtml(value);
                        return zl;
                    }, width: 50}
            ]
        ],
        onSelect: function (rowIndex, rowData) {
            //获取每个单元格
            $("#jgd_mx").edatagrid('editRow', rowIndex);
            var editors = $("#jgd_mx").datagrid('getEditors', rowIndex);
            if (editors.length == 0)
                return;
            var sbslEditor = editors[0];
            var sbzlEditor = editors[1];
            sbslEditor.target.unbind('blur').bind('blur', function () {
                $(sbslEditor.target).numberbox('setValue', $(sbslEditor.target).val());
                if (!$(sbslEditor.target).numberbox('getValue')) {
                    $(sbslEditor.target).numberbox('setValue', rowData.sbsl);
                }
                countJgdSum(rowIndex, $(sbslEditor.target).numberbox('getValue'), $(sbzlEditor.target).numberbox('getValue'));
            });
            sbzlEditor.target.unbind('blur').bind('blur', function () {
                $(sbzlEditor.target).numberbox('setValue', $(sbzlEditor.target).val());
                if (!$(sbzlEditor.target).numberbox('getValue')) {
                    $(sbzlEditor.target).numberbox('setValue', rowData.sbzl);
                }
                countJgdSum(rowIndex, $(sbslEditor.target).numberbox('getValue'), $(sbzlEditor.target).numberbox('getValue'));
            });
        }
    })
}

//计算总量
function countJgdSum(index, value1, value2) {
    var sumsbsl = 0;
    var sumsbzl = 0;
    var data = $("#jgd_mx").edatagrid("getData");
    for (var i = 0; i < data.rows.length; i++) {
        var sbsl = parseFloat(data.rows[i]['sbsl']);
        var sbzl = parseFloat(data.rows[i]['sbzl']);
        if (i == index) {
            sbsl = parseFloat(value1);
            sbzl = parseFloat(value2);
        }
        sbsl = isNaN(sbsl) ? 0.00 : sbsl;
        sbzl = isNaN(sbzl) ? 0.00 : sbzl;
        sumsbsl += sbsl;
        sumsbzl += sbzl;
    }
    addFooter(sumsbsl, sumsbzl);
}

//页面js合计
function addFooter(sumsbsl, sumsbzl) {
    var footer = [
        {"jtwz.code": "合计", "sbsl": sumsbsl, "sbzl": sumsbzl}
    ];
    if (footer != null)
        $("#jgd_mx").edatagrid('reloadFooter', footer);
}
